package org.osomit.sacct.account.registry.impl;

import org.osomit.sacct.entity.ApplicationAccount;
import org.osomit.sacct.entity.ApplicationAccountRecord;

import java.util.*;

/**
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 * Date: Jul 1, 2009
 */
public class AccountCache {
    
    private String clientId;

    private final Map<String, ApplicationAccount> accountMap = Collections.synchronizedMap(new HashMap<String, ApplicationAccount>());

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public Map getAccountMap() {
        return accountMap;
    }

    public void addOrUpdateAccount(ApplicationAccount account){
        synchronized(this.accountMap){
            this.accountMap.put(account.getName(), account);
        }
    }

    public void addAllAccounts(List<ApplicationAccount> accounts){
        synchronized(this.accountMap){
            for(ApplicationAccount account: accounts){
                this.accountMap.put(account.getName(), account);
            }
        }
    }

    public ApplicationAccount getAccount(String name){
        synchronized(this.accountMap){
            return this.accountMap.get(name);
        }
    }

    public List<ApplicationAccount> getAllAccounts(){
        List<ApplicationAccount> accounts = new ArrayList<ApplicationAccount>();
        synchronized(this.accountMap){
            accounts.addAll(this.accountMap.values());
        }

        return accounts;
    }

    public ApplicationAccountRecord getApplicationAccountRecord(){
        ApplicationAccountRecord record = new ApplicationAccountRecord();
        record.setClientId(this.clientId);
        record.setAccounts(this.getAllAccounts());

        return record;
    }

    public void deleteAccount(String name){
        synchronized (this.accountMap) {
            this.accountMap.remove(name);
        }    
    }

    public int size(){
        
        return this.accountMap.size();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AccountCache that = (AccountCache) o;

        if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = clientId != null ? clientId.hashCode() : 0;
        result = 31 * result + (accountMap != null ? accountMap.hashCode() : 0);
        return result;
    }
}
